{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#-*- coding: UTF-8 -*-\n",
    "# replace the words of the files\n",
    "\n",
    "#1 read file list\n",
    "#2 read words and replaced words list\n",
    "#3 find and output the words which will be replaced\n",
    "#4 waiting for checking the output words\n",
    "#5 Exit or Replace\n",
    "\n",
    "import pandas as pd\n",
    "import sys,os\n",
    "\n",
    "workDir = r'D:\\00-code\\dzqASO\\source\\optMethods\\GA_IP'\n",
    "\n",
    "#1 read file list\n",
    "# file list could be obtained by:\n",
    "# Linux: ls > fileList.csv\n",
    "# Win: dir /b > fileList.csv\n",
    "fileList = pd.read_csv(\"fileList.csv\",names=['fileName'])\n",
    "\n",
    "#2 read words and replaced words list\n",
    "# which is a CSV file, named replaceVarList.csv, format is like this:\n",
    "# original   replaced\n",
    "#  one          1\n",
    "#  two          2\n",
    "#   .           .\n",
    "#   .           .\n",
    "#   .           .\n",
    "replaceVarNameList = pd.read_csv('replaceVarList.csv')\n",
    "\n",
    "#3 find and output the words which will be replaced\n",
    "checkVar = pd.DataFrame(columns=('origVari','replVari','fileName','noLine','line'))\n",
    "checkVarDict = {'origVari':[],'replVari':[],'fileName':[],'noLine':[],'line':[]}\n",
    "for replacedVar in replaceVarNameList.itertuples():\n",
    "    oriVar = replacedVar[1]\n",
    "    replVari = replacedVar[2]\n",
    "    for fileName in fileList.itertuples():\n",
    "        with open(os.path.join(workDir,fileName[1]),'r',encoding='utf8') as openFile:\n",
    "            noLine = 0\n",
    "            for line in openFile.readlines():\n",
    "                noLine += 1\n",
    "                if oriVar in line:\n",
    "                    #print('aaa')\n",
    "                    checkVarDict['origVari'].append(oriVar)\n",
    "                    checkVarDict['replVari'].append(replVari)\n",
    "                    checkVarDict['fileName'].append(fileName[1])\n",
    "                    checkVarDict['noLine'].append(noLine)\n",
    "                    checkVarDict['line'].append(line.strip())\n",
    "#get DataFrame from dict\n",
    "checkVar = pd.DataFrame.from_dict(checkVarDict)\n",
    "#multi-index\n",
    "checkVar.set_index(['origVari','replVari','fileName','noLine'],inplace=True)\n",
    "#save to file\n",
    "checkVar.to_csv('checkVar.csv',sep=',',header=True)\n",
    "\n",
    "#4 waiting for checking the output words\n",
    "a = input('按回车继续（q退出修改）')\n",
    "if a == 'q' or a =='Q':\n",
    "    sys.exit()\n",
    "    \n",
    "#5 Exit or Replace\n",
    "#replace\n",
    "#replVari = pd.DataFrame.from_dict(checkVarDict)\n",
    "#replVari.set_index(['origVari','fileName'],inplace=True)\n",
    "checkedVar = pd.read_csv(os.path.join(workDir,'checkVar.csv'))\n",
    "checkedVar.set_index(['origVari','replVari','fileName','noLine'],inplace=True)\n",
    "for replacedVar in checkedVar.itertuples():\n",
    "    #print(replacedVar[0],replacedVar[1])\n",
    "    origVari = replacedVar[0][0]  # original variable name\n",
    "    replVari = replacedVar[0][1]  # replaced variable\n",
    "    fileName = replacedVar[0][2]  # file name\n",
    "    noLineRepl = replacedVar[0][3]  #line No.\n",
    "    newFile = ''\n",
    "    with open(os.path.join(workDir,fileName),'r+',encoding='utf8') as openFile:\n",
    "        noLine = 0\n",
    "        for line in openFile.readlines():            \n",
    "            noLine += 1\n",
    "            if noLine == noLineRepl:\n",
    "                newline = line.replace(origVari,replVari)\n",
    "            else:\n",
    "                newline = line\n",
    "            \n",
    "            newFile += newline\n",
    "        \n",
    "        openFile.seek(0)\n",
    "        openFile.writelines(newFile)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 214,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('nvar', 'bin2Dec.f90', 1) SUBROUTINE bin2Dec(chrom,chromsize,var,nvar)\n",
      "\n",
      "('nvar', 'bin2Dec.f90', 7)   INTEGER(I4B), INTENT(IN) :: chromsize,nvar\n",
      "\n",
      "('nvar', 'bin2Dec.f90', 9)   INTEGER(I4B), INTENT(OUT) :: var(nvar)\n",
      "\n",
      "('nvar', 'bin2Dec.f90', 15)   var_loop: do nv=1,nvar\n",
      "\n",
      "('nvar', 'dec2Bin.f90', 1) SUBROUTINE dec2Bin(chrom,chromsize,var,nvar)\n",
      "\n",
      "('nvar', 'dec2Bin.f90', 11)   INTEGER(I4B), INTENT(IN) :: chromsize,nvar\n",
      "\n",
      "('nvar', 'dec2Bin.f90', 12)   INTEGER(I4B), INTENT(IN) :: var(nvar)\n",
      "\n",
      "('nvar', 'GA.f90', 4)   use GA_global, ONLY: oldpop,newpop,bestfit,maxgen,gen,nvar, &\n",
      "\n",
      "('nvar', 'GA.f90', 172)       nvar_loop: do j=1,nvar\n",
      "\n",
      "('nvar', 'GA.f90', 175)       enddo nvar_loop\n",
      "\n",
      "('nvar', 'GA_continue.f90', 3)   use GA_global, ONLY: popsize,nvar,oldpop,bestfit, &\n",
      "\n",
      "('nvar', 'GA_continue.f90', 27)   READ(fp_continue,*) ((oldpop(i)%variable(j),j=1,nvar), &\n",
      "\n",
      "('nvar', 'GA_continue.f90', 38)   READ(fp_continue,*) (bestfit%variable(j),j=1,nvar)\n",
      "\n",
      "('nvar', 'GA_generation.f90', 5)                        chromsize,nvar,imulti,nfunc\n",
      "\n",
      "('nvar', 'GA_generation.f90', 23)       USE GA_global, ONLY: popsize,chromsize,nvar,&\n",
      "\n",
      "('nvar', 'GA_generation.f90', 102)   USE GA_global, ONLY: popsize,chromsize,nvar,&\n",
      "\n",
      "('nvar', 'GA_generation.f90', 131)              poptemp(i)%variable(nvar),  &\n",
      "\n",
      "('nvar', 'GA_generation.f90', 146)     nvar_loop: do j=1,nvar\n",
      "\n",
      "('nvar', 'GA_generation.f90', 148)     enddo nvar_loop\n",
      "\n",
      "('nvar', 'GA_generation.f90', 169)     nvar_loop2: do j=1,nvar\n",
      "\n",
      "('nvar', 'GA_generation.f90', 171)     enddo nvar_loop2\n",
      "\n",
      "('nvar', 'GA_global.f90', 39)   integer(I4B)     :: nvar !the number of variables\n",
      "\n",
      "('nvar', 'GA_initpop.f90', 5)        nfunc,imulti,nvar,xmin,xmax,&\n",
      "\n",
      "('nvar', 'GA_initpop.f90', 34)         var_loop0: DO nv=1, nvar\n",
      "\n",
      "('nvar', 'GA_initpop.f90', 42)         CALL bin2Dec(oldpop(j)%chrom,chromsize,oldpop(j)%variable,nvar)\n",
      "\n",
      "('nvar', 'GA_initpop.f90', 61)         var_loop: DO nv=1, nvar\n",
      "\n",
      "('nvar', 'GA_initpop.f90', 69)         CALL bin2Dec(oldpop(j)%chrom,chromsize,oldpop(j)%variable,nvar)\n",
      "\n",
      "('nvar', 'GA_input.f90', 9)     use GA_global, ONLY: popsize,sin_chromsize,nvar,oldpop,newpop,&\n",
      "\n",
      "('nvar', 'GA_input.f90', 20)   namelist /GA/ popsize,nvar,pcross,pmutation,&\n",
      "\n",
      "('nvar', 'GA_input.f90', 32)   !allocate(xmin(nvar),xmax(nvar),sin_chromsize(nvar))\n",
      "\n",
      "('nvar', 'GA_input.f90', 36)   !do i=1,nvar\n",
      "\n",
      "('nvar', 'GA_input.f90', 57)   allocate(xmin(nvar),xmax(nvar),sin_chromsize(nvar))\n",
      "\n",
      "('nvar', 'GA_input.f90', 92)   DO nv=1, nvar\n",
      "\n",
      "('nvar', 'GA_input.f90', 107)     allocate(oldpop(i)%variable(nvar),newpop(i)%variable(nvar))\n",
      "\n",
      "('nvar', 'GA_input.f90', 124)   allocate(bestfit%variable(nvar))\n",
      "\n",
      "('nvar', 'GA_input.f90', 139)   DO i=1, nvar\n",
      "\n",
      "('nvar', 'GA_objfunc.f90', 9)   use GA_global, ONLY: nvar,chromsize,imulti,nfunc,lin_weight,&\n",
      "\n",
      "('nvar', 'GA_objfunc.f90', 21)   CALL bin2Dec(pop%chrom,chromsize,pop%variable,nvar)\n",
      "\n",
      "('nvar', 'GA_objfunc.f90', 28)        nvar,nConstraint,1)\n",
      "\n",
      "('nvar', 'GA_output.f90', 6)   use GA_global, ONLY: popsize,oldpop,nvar,bestfit,chromsize, &\n",
      "\n",
      "('nvar', 'GA_output.f90', 42)   WRITE(fp_output,*) ((oldpop(i)%variable(j),j=1,nvar), &\n",
      "\n",
      "('nvar', 'GA_output.f90', 56)   WRITE(fp_output,*) (bestfit%variable(j),j=1,nvar)\n",
      "\n",
      "('nvar', 'GA_output.f90', 62) !           poptmp%variable(nvar)  , &\n",
      "\n",
      "('nvar', 'GA_output.f90', 88) !      do j=1,nvar\n",
      "\n",
      "('nWriteFile', 'GA.f90', 6)                        ncross,nmutation,fp_fit,start_gen,nWriteFile,&\n",
      "\n",
      "('nWriteFile', 'GA.f90', 117)     if(mod(gen,nWriteFile)==0 .OR. gen>maxgen)then\n",
      "\n",
      "('nWriteFile', 'GA_global.f90', 83)   INTEGER(I4B)     :: nWriteFile !每隔多少步保存一次结果\n",
      "\n",
      "('nWriteFile', 'GA_input.f90', 12)                        nWriteFile,nfunc,nConstraint,lin_weight,func, &\n",
      "\n",
      "('nWriteFile', 'GA_input.f90', 22)                 nWriteFile,lin_weight,nConstraint,&\n",
      "\n"
     ]
    }
   ],
   "source": [
    "for replacedVar in checkVar.itertuples():\n",
    "    print(replacedVar[0],replacedVar[1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
